<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI文件问答助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/daisyui/4.12.10/full.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .drag-area {
            border: 2px dashed #d1d5db;
            transition: all 0.3s ease;
        }
        .drag-area.dragover {
            border-color: #3b82f6;
            background-color: #eff6ff;
        }
        .message {
            animation: fadeIn 0.3s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .source-card {
            transition: all 0.2s ease;
        }
        .source-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- 标题区域 -->
        <div class="text-center mb-8">
            <h1 class="text-4xl font-bold text-gray-800 mb-2">
                <i class="fas fa-robot text-blue-600 mr-3"></i>AI文件问答助手
            </h1>
            <p class="text-gray-600">上传您的文档，AI帮您快速找到答案</p>
        </div>

        <!-- 状态栏 -->
        <div class="bg-white rounded-lg shadow-md p-4 mb-6">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <div class="flex items-center">
                        <div id="status-indicator" class="w-3 h-3 rounded-full bg-green-500 mr-2"></div>
                        <span id="status-text" class="text-sm text-gray-600">系统就绪</span>
                    </div>
                    <div class="text-sm text-gray-500">
                        文档数量: <span id="doc-count" class="font-semibold">0</span>
                    </div>
                </div>
                <button id="clear-btn" class="btn btn-sm btn-ghost text-red-600">
                    <i class="fas fa-trash mr-1"></i>清除所有
                </button>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 左侧：文件上传区域 -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">
                    <i class="fas fa-upload mr-2"></i>文件上传
                </h2>
                
                <!-- 拖拽区域 -->
                <div id="drag-area" class="drag-area rounded-lg p-8 text-center mb-4">
                    <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-4"></i>
                    <p class="text-gray-600 mb-2">拖拽文件到此处或</p>
                    <button id="select-files-btn" class="btn btn-primary btn-sm">
                        <i class="fas fa-folder-open mr-1"></i>选择文件
                    </button>
                    <p class="text-xs text-gray-500 mt-2">支持 txt, pdf, md, docx 格式</p>
                </div>

                <!-- 文件列表 -->
                <div id="file-list" class="space-y-2 mb-4 hidden">
                    <h3 class="font-semibold text-gray-700">已选择文件：</h3>
                    <div id="file-items"></div>
                </div>

                <!-- 上传按钮 -->
                <button id="upload-btn" class="btn btn-primary w-full hidden">
                    <i class="fas fa-upload mr-2"></i>开始上传
                </button>

                <!-- 进度条 -->
                <div id="progress-container" class="hidden mt-4">
                    <div class="flex justify-between text-sm text-gray-600 mb-1">
                        <span>上传进度</span>
                        <span id="progress-text">0%</span>
                    </div>
                    <progress id="progress-bar" class="progress progress-primary w-full" value="0" max="100"></progress>
                </div>
            </div>

            <!-- 右侧：问答区域 -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">
                    <i class="fas fa-comments mr-2"></i>智能问答
                </h2>

                <!-- 问题输入 -->
                <div class="form-control mb-4">
                    <label class="label">
                        <span class="label-text">请输入您的问题</span>
                    </label>
                    <textarea 
                        id="question-input" 
                        class="textarea textarea-bordered h-24" 
                        placeholder="例如：这份文档的主要内容是什么？"
                    ></textarea>
                </div>

                <!-- 提问按钮 -->
                <button id="ask-btn" class="btn btn-secondary w-full mb-4">
                    <i class="fas fa-paper-plane mr-2"></i>提问
                </button>

                <!-- 答案显示区域 -->
                <div id="answer-container" class="hidden">
                    <div class="divider"></div>
                    <h3 class="font-semibold text-gray-700 mb-3">
                        <i class="fas fa-lightbulb mr-2"></i>AI回答
                    </h3>
                    <div id="answer-content" class="bg-gray-50 rounded-lg p-4 mb-4">
                        <!-- 答案内容将在这里显示 -->
                    </div>

                    <!-- 来源信息 -->
                    <div id="sources-container" class="hidden">
                        <h4 class="font-semibold text-gray-700 mb-2">
                            <i class="fas fa-link mr-2"></i>参考来源
                        </h4>
                        <div id="sources-list" class="space-y-2">
                            <!-- 来源列表将在这里显示 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 隐藏的文件输入 -->
    <input type="file" id="file-input" multiple accept=".txt,.pdf,.md,.docx" class="hidden">

    <script>
        // API配置
        const API_BASE = 'http://localhost:8000/api';
        
        // 全局变量
        let selectedFiles = [];
        let isProcessing = false;

        // DOM元素
        const dragArea = document.getElementById('drag-area');
        const fileInput = document.getElementById('file-input');
        const selectFilesBtn = document.getElementById('select-files-btn');
        const fileList = document.getElementById('file-list');
        const fileItems = document.getElementById('file-items');
        const uploadBtn = document.getElementById('upload-btn');
        const progressContainer = document.getElementById('progress-container');
        const progressBar = document.getElementById('progress-bar');
        const progressText = document.getElementById('progress-text');
        const questionInput = document.getElementById('question-input');
        const askBtn = document.getElementById('ask-btn');
        const answerContainer = document.getElementById('answer-container');
        const answerContent = document.getElementById('answer-content');
        const sourcesContainer = document.getElementById('sources-container');
        const sourcesList = document.getElementById('sources-list');
        const statusText = document.getElementById('status-text');
        const docCount = document.getElementById('doc-count');
        const clearBtn = document.getElementById('clear-btn');

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateStatus();
            setupEventListeners();
        });

        // 设置事件监听器
        function setupEventListeners() {
            // 文件选择
            selectFilesBtn.addEventListener('click', () => fileInput.click());
            fileInput.addEventListener('change', handleFileSelect);

            // 拖拽功能
            dragArea.addEventListener('dragover', handleDragOver);
            dragArea.addEventListener('dragleave', handleDragLeave);
            dragArea.addEventListener('drop', handleDrop);

            // 上传按钮
            uploadBtn.addEventListener('click', uploadFiles);

            // 提问按钮
            askBtn.addEventListener('click', askQuestion);

            // 清除按钮
            clearBtn.addEventListener('click', clearAll);

            // 回车提问
            questionInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    askQuestion();
                }
            });
        }

        // 文件选择处理
        function handleFileSelect(e) {
            const files = Array.from(e.target.files);
            addFiles(files);
        }

        // 拖拽处理
        function handleDragOver(e) {
            e.preventDefault();
            dragArea.classList.add('dragover');
        }

        function handleDragLeave(e) {
            e.preventDefault();
            dragArea.classList.remove('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            dragArea.classList.remove('dragover');
            const files = Array.from(e.dataTransfer.files);
            addFiles(files);
        }

        // 添加文件
        function addFiles(files) {
            const validFiles = files.filter(file => {
                const validTypes = ['.txt', '.pdf', '.md', '.docx'];
                const extension = '.' + file.name.split('.').pop().toLowerCase();
                return validTypes.includes(extension);
            });

            if (validFiles.length !== files.length) {
                alert('部分文件格式不支持，只接受 txt, pdf, md, docx 格式');
            }

            selectedFiles = [...selectedFiles, ...validFiles];
            updateFileList();
        }

        // 更新文件列表
        function updateFileList() {
            if (selectedFiles.length === 0) {
                fileList.classList.add('hidden');
                uploadBtn.classList.add('hidden');
                return;
            }

            fileList.classList.remove('hidden');
            uploadBtn.classList.remove('hidden');

            fileItems.innerHTML = selectedFiles.map((file, index) => `
                <div class="flex items-center justify-between bg-gray-50 rounded p-2">
                    <div class="flex items-center">
                        <i class="fas fa-file text-blue-500 mr-2"></i>
                        <span class="text-sm">${file.name}</span>
                        <span class="text-xs text-gray-500 ml-2">(${(file.size / 1024).toFixed(1)} KB)</span>
                    </div>
                    <button onclick="removeFile(${index})" class="btn btn-ghost btn-xs text-red-500">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            `).join('');
        }

        // 移除文件
        function removeFile(index) {
            selectedFiles.splice(index, 1);
            updateFileList();
        }

        // 上传文件
        async function uploadFiles() {
            if (selectedFiles.length === 0) {
                alert('请先选择文件');
                return;
            }

            if (isProcessing) return;

            isProcessing = true;
            uploadBtn.disabled = true;
            progressContainer.classList.remove('hidden');

            const formData = new FormData();
            selectedFiles.forEach(file => {
                formData.append('files', file);
            });

            try {
                const response = await fetch(`${API_BASE}/upload`, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (response.ok) {
                    showMessage('success', `成功上传 ${result.files.length} 个文件`);
                    selectedFiles = [];
                    updateFileList();
                    updateStatus();
                } else {
                    showMessage('error', result.detail || '上传失败');
                }
            } catch (error) {
                showMessage('error', '上传失败: ' + error.message);
            } finally {
                isProcessing = false;
                uploadBtn.disabled = false;
                progressContainer.classList.add('hidden');
                progressBar.value = 0;
                progressText.textContent = '0%';
            }
        }

        // 提问
        async function askQuestion() {
            const question = questionInput.value.trim();
            if (!question) {
                alert('请输入问题');
                return;
            }

            askBtn.disabled = true;
            askBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>思考中...';

            try {
                const formData = new FormData();
                formData.append('question', question);

                const response = await fetch(`${API_BASE}/ask`, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (response.ok) {
                    displayAnswer(result);
                } else {
                    showMessage('error', result.detail || '提问失败');
                }
            } catch (error) {
                showMessage('error', '提问失败: ' + error.message);
            } finally {
                askBtn.disabled = false;
                askBtn.innerHTML = '<i class="fas fa-paper-plane mr-2"></i>提问';
            }
        }

        // 显示答案
        function displayAnswer(result) {
            answerContent.innerHTML = result.answer.replace(/\n/g, '<br>');
            answerContainer.classList.remove('hidden');

            // 显示来源
            if (result.sources && result.sources.length > 0) {
                sourcesList.innerHTML = result.sources.map(source => `
                    <div class="source-card bg-gray-50 rounded-lg p-3 border">
                        <div class="flex items-center justify-between mb-2">
                            <div class="flex items-center">
                                <i class="fas fa-file-alt text-blue-500 mr-2"></i>
                                <span class="font-medium text-sm">${source.file}</span>
                            </div>
                            <span class="text-xs text-gray-500">相似度: ${(source.score * 100).toFixed(1)}%</span>
                        </div>
                        <p class="text-sm text-gray-700">${source.content}</p>
                    </div>
                `).join('');
                sourcesContainer.classList.remove('hidden');
            } else {
                sourcesContainer.classList.add('hidden');
            }

            // 滚动到答案区域
            answerContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }

        // 更新状态
        async function updateStatus() {
            try {
                const response = await fetch(`${API_BASE}/status`);
                const result = await response.json();
                
                if (response.ok) {
                    docCount.textContent = result.documents_count;
                    if (result.documents_count > 0) {
                        statusText.textContent = `已加载 ${result.documents_count} 个文档`;
                    } else {
                        statusText.textContent = '系统就绪';
                    }
                }
            } catch (error) {
                console.error('获取状态失败:', error);
            }
        }

        // 清除所有
        async function clearAll() {
            if (!confirm('确定要清除所有文档吗？此操作不可恢复。')) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/clear`, {
                    method: 'DELETE'
                });

                const result = await response.json();

                if (response.ok) {
                    showMessage('success', result.message);
                    answerContainer.classList.add('hidden');
                    updateStatus();
                } else {
                    showMessage('error', result.detail || '清除失败');
                }
            } catch (error) {
                showMessage('error', '清除失败: ' + error.message);
            }
        }

        // 显示消息
        function showMessage(type, message) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message alert alert-${type === 'success' ? 'success' : 'error'} mb-4`;
            messageDiv.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} mr-2"></i>
                <span>${message}</span>
            `;
            
            document.querySelector('.container').insertBefore(messageDiv, document.querySelector('.grid'));
            
            setTimeout(() => {
                messageDiv.remove();
            }, 3000);
        }

        // 定期更新状态
        setInterval(updateStatus, 30000); // 每30秒更新一次状态
    </script>
</body>
</html>
